# -*- coding: utf-8 -*-
"""
Created on Wed Jun 11 17:48:23 2014

@author: Adrien
"""

import csv
import DatabaseHandlerInterface as DBHi
import DataModel as Model
import Tkinter
import ttk
import tkFileDialog
import re

class CosmicFusionExport(DBHi.DatabasePluginInterface):
    
     def __init__(self):
        self._options={'path':''}
        self._data=None
        self._headers=[]
     
     def setConfigDoneFunction(self,func):
        self.configDoneFunction=func
    
     def getData(self):
         if self._data==None:
             self.readFile()
         return self._data
     
     def readFile(self):
         _delimiter = '\t'
         filePath=self._options['path']
         fileobj=openFile(filePath,'rb')
         self._data={'genes':[],'fusions':[]}
         cr = csv.reader(fileobj,delimiter=_delimiter)
         rownum=0
         for row in cr:
             if rownum == 0:
                 self._headers = row
             else:
                 pattern= re.compile('(.*){(.*)}:r.(.*)_(.*){(.*)}:r.(.*)')
                 m = pattern.match(row[7])
                 if m !=None:
                     nameA = m.group(1)
                     nameB = m.group(4)
                     geneA =Model.Gene(nameA)
                     geneB=Model.Gene(nameB)
                     breakPointA =m.group(3)
                     breakPointB=m.group(6)
                     fusion = Model.Fusion(nameA,nameB,breakpointA=breakPointA, strandA="", fusionDirectionA="",breakpointB=breakPointB, strandB="", fusionDirectionB="",notes="")
                     if geneA not in self._data['genes']:
                         self._data['genes'].append(geneA)
                     if geneB not in self._data['genes']:
                         self._data['genes'].append(geneB)
                     self._data['fusions'].append(fusion)
             rownum+=1
         return self._data
     def setData(self,data):
         self._data=data
    
     def getOptionPanel(self,parent):
         self.v = Tkinter.StringVar()
         self.y = Tkinter.StringVar()
         self.y.set(self._options['path'])
         self.optionPanelIn=ttk.Frame(parent)
         title = ttk.Label(self.optionPanelIn,text="Cosmic Fusion Export")
         label0 = ttk.Label(self.optionPanelIn,text="Database file path:")
         ent0 = ttk.Entry(self.optionPanelIn,textvariable=self.y)
         
         browseBtn = ttk.Button(self.optionPanelIn, text="Browse...",command=self.browse)
         selectBtn = ttk.Button(self.optionPanelIn, text="OK",command=self.select)
         abortBtn = ttk.Button(self.optionPanelIn, text="Cancel",command=self.optionPanelIn.destroy)
         
         title.pack()
         label0.pack()
         ent0.pack(fill=Tkinter.X)
         browseBtn.pack()
         selectBtn.pack(fill=Tkinter.X)
         abortBtn.pack(fill=Tkinter.X)
         
         self.optionPanelIn.pack(side="top", fill="both", expand=1)
         return self.optionPanelIn
    
     def browse(self):
        dir_opt = options = {}
        options['initialdir'] = self.v.get()
        options['title'] = 'Select CosmicFusionExport.tsv:'
        options['parent'] = self.optionPanelIn
        directory=tkFileDialog.askopenfilename(**dir_opt)
        if directory != None and directory!="":
            self.y.set(directory)
         
     def select(self):
         self._options['path']=self.y.get()
         self.configDoneFunction()
             
     def setConfig(self,options):
         self._options=options
     
     def getConfig(self):
         return self._options




def openFile(path,mode):
     try:
         myFileobj = open(path,mode)
         return myFileobj
     except IOError:
             raise Exception('cannot open file')  
    